package springinpractice.ch4.r4_3.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import springinpractice.ch4.r4_3.dao.UserDao;
import springinpractice.ch4.r4_3.model.User;

/*
 * Author       :       Willie Wheeler and John Wheeler
 * Book         :       'Spring In Practice' [Book written by Willie Wheeler and John Wheeler]
 */

@Service("userService")
@Transactional(
		propagation = Propagation.REQUIRED,
		isolation = Isolation.DEFAULT,
		readOnly = true)
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserDao userDao;
	
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Transactional(readOnly = false)	
	public void registerUserIfValid(User user, boolean userIsValid)
			throws DuplicateRegistrationException {
		
		boolean usernameTaken =
			(userDao.findByUsername(user.getUsername()) != null);
		boolean emailTaken =
			(userDao.findByEmail(user.getEmail()) != null);
		
		if (usernameTaken || emailTaken) {
			throw new DuplicateRegistrationException(usernameTaken, emailTaken);
		}
		
		if (userIsValid) {
			userDao.save(user);
		}
	}
}
